
package com.jf.cloud.multishop.controller.multishop;

import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.PriceUtil;
import com.jf.cloud.multishop.bo.mongo.MongoShopWalletLogBO;
import com.jf.cloud.multishop.constant.ShopWalletAmountType;
import com.jf.cloud.multishop.constant.ShopWalletChangeReason;
import com.jf.cloud.multishop.constant.ShopWalletIoType;
import com.jf.cloud.multishop.service.ShopWalletLogService;
import com.jf.cloud.multishop.service.ShopWalletService;
import com.jf.cloud.multishop.vo.ShopWalletVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 商家店铺余额充值级别表
 *
 * @author zz
 * @date 2022-06-30 15:51:36
 */
@RestController("multishopRechargeController")
@RequestMapping("/m/shop_recharge")
@Tag(name = "multishop-商家余额充值")
public class ShopRechargeController {

    @Autowired
    private ShopWalletLogService shopWalletLogService;
    @Autowired
    private ShopWalletService shopWalletService;


    @PostMapping("/recharge")
    @Operation(summary = "充值订单" , description = "生成余额充值订单，保存充值记录")
    public ServerResponseEntity<Long> save(@Valid @RequestParam BigDecimal rechargeAmount) {
        Long amount = PriceUtil.toLongCent(rechargeAmount);
        if (amount < 1) {
            throw new LuckException("充值金额有误");
        }
        Long shopId = AuthUserContext.get().getTenantId();
        ShopWalletVO shopWallet = shopWalletService.getByShopId(shopId);
        long userBalance = shopWallet.getSettledAmount() + amount;

        if (userBalance > Constant.MAX_USER_BALANCE) {
            throw new LuckException("此次充值会导致余额超出最大限制，故无法进行此操作,请减少充值金额后重试");
        }
        MongoShopWalletLogBO shopWalletLog = new MongoShopWalletLogBO();
        shopWalletLog.setShopId(shopId);
        shopWalletLog.setShopChangeAmount(amount);
        shopWalletLog.setUserAmount(amount);
        shopWalletLog.setShopIoType(ShopWalletIoType.INCOME.value());
        shopWalletLog.setReason(ShopWalletChangeReason.APPLY_RECHARGE.value());
        shopWalletLog.setAmountType(ShopWalletAmountType.SETTLED_AMOUNT.value());
        shopWalletLog.setCreateTime(new Date());
        shopWalletLogService.saveMongo(shopWalletLog);
        return ServerResponseEntity.success(shopWalletLog.getWalletLogId());
    }


}
